<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/common/taglibs.jsp" %>
<!DOCTYPE html>
<html>
<head>
<title><s:text name="system.index.title"/></title>
<%@ include file="/common/meta-gs.jsp" %>
<script type="text/javascript">
var operMethod="view";
var _userList={};
var _taskTypeDict = {"1":"普通任务","2":"预警通知任务","3":"百度地图GPS地址更新任务"};
function getOption() {
	return {
		title:'<s:text name="任务"/>',
		width:600,
		height:350,
		nowrap: false,
		striped: true,
		fit: true,
		url:'${ctx}/sys/task/task!queryList.action',
		sortName: 'id',
		sortOrder: 'desc',
		idField:'id',
		frozenColumns:[[
          {field:'ck',checkbox:true}
		]],
		columns:[[
					{field:'name',title:'<s:text name="任务名称"/>',width:160},
					{field:'taskType',title:'<s:text name="任务类型"/>',width:100,
					 formatter:function(value,rowData,rowIndex){
						var val = _taskTypeDict[value];
						if(val) {
							return val;
						} else {
							return "";
						}
					}},
					{field:'remark',title:'<s:text name="任务描述"/>',width:200},
					{field:'createTime',title:'<s:text name="创建时间"/>',width:120,align:'center'},
					{field:'createUser',title:'<s:text name="创建者"/>',width:120,formatter:formatterUser},
					//{field:'lastUpdateTime',title:'<s:text name="上次修改时间"/>',width:150,align:'center'},
					//{field:'lastUpdateUser',title:'<s:text name="上次修改者"/>',width:150,formatter:formatterUser},
					{
						field : 'oper',
						title : '<s:text name="system.button.oper.title"/>',
						width : 250,
						align : 'center',
						formatter : operFormatter
					}
				]],
		toolbar : [
				'-'
				,{
				    id : 'bt_add',
				    text : '<s:text name="system.button.add.title"/>(I)',
				    iconCls : 'icon-add',
				    handler : function() {
				        doAdd();
				    }
				}
				,
				{
				    id : 'bt_del',
				    text : '<s:text name="system.button.delete.title"/>(D)',
				    iconCls : 'icon-remove',
				    handler : function() {
				        doDelete();
				    }                           
				}
				,
				{
				    id : 'bt_view',
				    text : '<s:text name="system.button.view.title"/>(E)',
				    iconCls : "icon-search",
				    handler : function() {
				        doView();
				    }
				}
		],		
		pagination:true,
		rownumbers:true,
		onDblClickRow:function(rowIndex, rowData){
        	doDblView(rowData.id);
        	//$('#queryList').datagrid('unselectRow',rowIndex);
        }
	};
}

function operFormatter(value, rowData, rowIndex){
	var strArr = [];
	strArr.push('<a href="javascript:void(0);" onclick="doDblView(');
	strArr.push(rowData.id);
	strArr.push(')"><s:text name="system.button.view.title"/></a>');
	strArr.push('&nbsp;<a href="javascript:void(0);" onclick="doEdit(');
	strArr.push(rowData.id);
	strArr.push(')"><s:text name="system.button.modify.title"/></a>');
	strArr.push('&nbsp;<a href="javascript:void(0);" onclick="doDelete(');
	strArr.push(rowData.id);
	strArr.push(')"><s:text name="system.button.delete.title"/></a>');
	return strArr.join("");
}

function formatterUser(value, rowData, rowIndex){
    /*var uObj=_userList[value];
    if(uObj){
        return uObj.realName + "[" + uObj.loginName + "]";
    }else{
        return value;
    }*/
    return rowData["createUserCaption"];
}

function doChangeTaskType(val) {
	$("#normalTask").hide();
	$("#noticeTask").hide();
	$("#gpsUpdateTask").hide();
	switch(val) {
		case "1":
			$("#normalTask").show();
			break;
		case "2":
			$("#noticeTask").show();
			break;
		case "3":
			$("#gpsUpdateTask").show();
			break;
		default:
			break;	
	}
}

function checkValues(){
	var obj = {};
	var taskTypeVal = $("#taskType").combobox("getValue");
  	if (taskTypeVal == "1") {
	   var executeTypeVal = $("#executeType").combobox("getValue");
  	   if(!executeTypeVal) {
  		 	$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请选择执行类型','info');
  		 	return false;
	   }
  	   var executeContentVal = $("#executeContent").val();
  	   if(!executeContentVal) {
  		 	$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请填写执行内容','info');
		 	return false;
  	   }
  	   obj["executeType"] = executeTypeVal;
  	   obj["executeContent"] = executeContentVal;
  	   obj["executeParam"] = $("#executeParam").val();
	} else if(taskTypeVal == "2") {
		   var moduleKeyVal = $("#moduleKey").val();
	  	   if(!moduleKeyVal) {
	  		 	$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请填写模块实体名','info');
	  		 	return false;
		   }
	  	   var querySqlVal = $("#querySql").val();
	  	   if(!querySqlVal) {
	  		 	$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请填写查询sql语句','info');
	  		 	return false;
		   }
	  	   var noticeValVal = $("#noticeVal").val();
	  	   if(!noticeValVal) {
	  		 	$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请填写通知内容','info');
	  		 	return false;
		   }
	  	   var destTypeVal = $("#destType").combobox("getValue");
	  	   if(!destTypeVal) {
	  		 	$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请选择通知目标类型','info');
	  		 	return false;
		   }
	  	   var destValVal = $("#destVal").val();
	  	   if(!destValVal) {
	  		 	$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请填写通知目标','info');
	  		 	return false;
		   }
	  	   obj["moduleKey"] = moduleKeyVal;
	  	   obj["querySql"] = querySqlVal;
	  	   obj["noticeVal"] = noticeValVal;
	  	   obj["destType"] = destTypeVal;
	  	   obj["destVal"] = destValVal;
	} else if(taskTypeVal == "3") {
		var querySql = $("#gpsQuerySql").val();
		if(!querySql) {
			$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请填写查询sql','info');
			return false;
		}
		var updateSql = $("#gpsUpdateSql").val();
		if(!updateSql) {
			$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请填写更新sql','info');
			return false;
		}
		var coordtype = jwpf.getFormVal("coordtype");
		if(!coordtype) {
			$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','请选择GPS坐标系类型','info');
			return false;
		}
		obj["querySql"] = querySql;
		obj["updateSql"] = updateSql;
		obj["executeType"] = coordtype;
	} else {
		$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>','不支持的任务类型','info');
		return false;
	}
    return obj;
}

function doQuery() {
	var param = $("#queryForm").serializeArrayToParam();
	$("#queryList").datagrid("load", param);
}

//新增
function doAdd() {
    operMethod = "add";
    var title = "<s:text name="system.button.add.title"/><s:text name="任务"/>";
	$("#detail_win").window("setTitle", title);
	$("#detail_win").window("open");
}

//修改
function doEdit(id) {
	operMethod = "modify";
	$("#detail_win").data("id", id);
	var title = "<s:text name="system.button.modify.title"/><s:text name="任务"/>";
	$("#detail_win").window("setTitle", title);
	$("#detail_win").window("open");
}

//查看
function doView() {
	 var id=0;
	 var rows = $('#queryList').datagrid('getSelections');
	  if(rows.length!=1){
		 $.messager.alert('<s:text name="system.javascript.alertinfo.title"/>', '<s:text name="system.javascript.alertinfo.view"/>', 'info');
	     return ;
	 } else{
		 id=rows[0].id;
	 }
	 doDblView(id); 
}

//查看tab
function doDblView(id) {
	operMethod = "view";
	$("#detail_win").data("id", id);
	var title = "<s:text name="system.button.view.title"/><s:text name="任务"/>";
	$("#detail_win").window("setTitle", title);
	$("#detail_win").window("open");
}

function clearAddField() {
	$("#id").val("");
	$("#atmId").val("");
	$("#flowInsId").val("");
	$("#status").val("10");
}

function doPrepareForm(jsonData) {
	var contentVal = jsonData["taskContent"];
	var obj = $.parseJSON(contentVal);
	$.extend(jsonData, obj);
	doChangeTaskType(jsonData["taskType"]);
}

function doInitForm(data, callFunc) {
	if (data.msg) {
          var jsonData = data.msg;
          doPrepareForm(jsonData);
          $('#viewForm').form('load',jsonData);
          if(operMethod == "edit") {
          	clearAddField();
          }
    }
    if(callFunc) {
    	callFunc();
    }
}		

//页面数据初始化
function doModify(id, callFunc) {
    	var options = {
          url : '${ctx}/sys/task/task!view.action',
          data : {
              "id" : id
          },
          success : function(data) {
              doInitForm(data, callFunc);
          }
     };
     fnFormAjaxWithJson(options);
}

//保存
function doSaveObj(){
	var obj = checkValues();
	if(obj) {
		var contentVal = JSON.stringify(obj);
		$("#taskContent").val(contentVal);
		var options = {
				url : '${ctx}/sys/task/task!save.action',
				success : function(data) {
					doAfterSave();
				}
		};
		fnAjaxSubmitWithJson("viewForm",options);
	}
}

//保存后继续新增
function doAfterSave() {
	doQuery();
	operMethod="add";
	doCloseWindow();
}

//删除一条记录
function doDelete(id) {
    var ids = [];
    if(id) {   
    	ids.push(id);
    } else {
        var rows = $('#queryList').datagrid('getSelections');
        for (var i = 0; i < rows.length; i++) {
        	if(rows[i].status == "1") {
        		$.messager.alert('<s:text name="system.javascript.alertinfo.title"/>', '<s:text name="运行状态的记录不能被删除，请先停止运行，再进行删除"/>', 'info');
        		return;
        	}
            ids.push(rows[i].id);
        }
    } 
    if (ids != null && ids.length > 0) {
        $.messager.confirm('<s:text name="system.javascript.alertinfo.title"/>', '<s:text name="system.javascript.alertinfo.info"/>', function(r) {
            if (r) {
                var options = {
                    url : '${ctx}/sys/task/task!delete.action',
                    data : {
                        "ids" : ids
                    },
                    success : function(data) {
                        if (data.msg) {
                            $('#queryList').datagrid('clearSelections');
                            doQuery();
                        }
                    },
                    traditional:true
                };
                fnFormAjaxWithJson(options);
            }
        })

    } else {
        $.messager.alert('<s:text name="system.javascript.alertinfo.title"/>', '<s:text name="system.javascript.alertinfo.question"/>', 'info');
    }
}

//关闭窗口
function doCloseWindow() {
	$("#detail_win").window("close");
}

function doEnable() {
    $("div.file_upload_button").show();
	$("input[type!=hidden],textarea,select").removeAttr("disabled");
	$("input.easyui-combobox").combobox('enable');
	$("select.easyui-combogrid").combogrid('enable');
	$("select.easyui-combotree").combotree('enable');
	$('input.Idate').addClass("Wdate");
	$(".jquery_ckeditor").each(function() {
		try {
			$(this).ckeditorGet().setReadOnly(false);
		} catch(e) {
			$(this).ckeditorGet().setReadOnly(false);
		}
	});
	$("#stSave").show();
}	

//将页面上的控件置为不可编辑状态
function doDisabled() {
    $("div.file_upload_button").hide();
	$("input[type!=hidden],textarea,select").attr("disabled", "disabled");
	$("input.easyui-combobox").combobox('disable');
	$("select.easyui-combogrid").combogrid('disable');
	$("select.easyui-combotree").combotree('disable');
	$('input.Idate').removeClass("Wdate");
	$(".jquery_ckeditor").each(function() {
		try {
			$(this).ckeditorGet().setReadOnly(true);
		} catch(e) {
			$(this).ckeditorGet().setReadOnly(true);
		}
	});
	$("#stSave").hide();
}

//设置焦点
function focusFirstElement() {
	if(operMethod != "view") {
			jwpf.focusFirstInputOnForm("viewForm");
		}
}	

function formClear() {
	$('#viewForm').form('clear');
	$("#status").val("10");
	$(".jquery_ckeditor").each(function() {
		try {
			$(this).ckeditorGet().setData("");
		} catch(e) {
			$(this).ckeditorGet().setData("");
		}
	});
	$("img.previewImageCls").attr("src", "");
}

function initDetailWindow() {
	$("#detail_win").window({
		onOpen:function() {
			$(this).window("move", {
				top:($(window).height()-550)*0.5,
				left:($(window).width()-650)*0.5
			});
			var id = $("#detail_win").data("id");
			switch(operMethod) {
				case "add"://新增
					focusFirstElement();
					break;
				case "view"://查看
					doModify(id, doDisabled);
					break;
				case "modify"://修改
					doModify(id, focusFirstElement);
					break;
				case "edit"://复制
					doModify(id, focusFirstElement);
					break;
				default:
					doModify(id, doDisabled);
			}
		},
		onClose:function() {
			doEnable();
			formClear();
		}
	});
}

$(document).ready(function() {
	//_userList=findAllUser();
	
	focusEditor("query_name");
    doQuseryAction("queryForm");
	
	$('#queryList').datagrid(getOption());
	
	initDetailWindow();
	
	$("#taskType").combobox({
		onChange:function(newVal, oldVal) {
			doChangeTaskType(newVal);
		}
	});
	
	$("#bt_query").click(doQuery);
	$("#bt_reset").click(function() {
		$("#queryForm")[0].reset();
		doQuery();
	});
	
});
	</script>
</head>
<body class="easyui-layout">
    <div region="west" border="false" title="<s:text name="system.search.title"/>" split="true" style="width:260px;padding:0px;" iconCls="icon-search">
			<form action="" name="queryForm" id="queryForm">
				<table border="0" cellpadding="0" cellspacing="1" class="table_form">
					<tbody>
						<tr>
							<th><label for="query_name"><s:text name="任务名称"/>:</label></th>
							<td><input type="text" name="filter_LIKES_name" id="query_name" class="Itext"></input></td>
						</tr>
						<tr>
							<th><label for="query_taskType"><s:text name="任务类型"/>:</label></th>
							<td><select id="query_taskType" class="easyui-combobox" name="filter_EQS_taskType" style="width:160px">
									<option value="">所有</option>
									<option value="1">普通任务</option>
									<option value="2">预警通知任务</option>
									<option value="3">百度地图GPS地址更新任务</option>
								</select>
							</td>
						</tr>
						<tr>		
							<td colspan="2" align="center">
								<button type="button" id="bt_query"><s:text name="system.search.button.title"/></button>&nbsp;&nbsp;
								<button type="button" id="bt_reset"><s:text name="system.search.reset.title"/></button>
							</td>
						</tr>
					</tbody>
				</table>
			</form>
	</div>
	<div region="center" border="false" title="" style="overflow:hidden;">
		<table id="queryList" border="false"></table>
	</div>
	<div style="display:none;">
		<div id="detail_win" closed="true" modal="true" title="任务设置" resizable="false" minimizable="false"
			iconCls="icon-save" style="width: 650px; height: 550px; padding: 0px; background: #fafafa;">
			<div class="easyui-layout" fit="true">
				<div region="center" border="false" style="padding:10px;background:#fff;border:1px solid #ccc;">
					<form action=""
					name="viewForm" id="viewForm" method="post">
					<input type="hidden" name="id" id="id"/>
					<input type="hidden" name="taskContent" id="taskContent"/>
					<table align="center" border="0" cellpadding="0" cellspacing="1"
						class="table_form">
						<tbody>
							<tr>
								<th><label for="name"><s:text
											name="任务名称" />:</label>
								</th>
								<td><input type="text" name="name"
									id="name" class="easyui-validatebox Itext" required="true" style="width:300px;"></input>
								</td>
							</tr>
							<tr>
								<th><label for="remark"><s:text
											name="任务描述" />:</label>
								</th>
								<td><textarea name="remark" id="remark" style="width:300px;height:80px;"></textarea>
								</td>
							</tr>
							<tr>
								<th><label for="taskType"><s:text
											name="任务类型" />:</label>
								</th>
								<td>
								<select id="taskType" name="taskType" style="width:160px">
									<option value="1">普通任务</option>
									<option value="2">预警通知任务</option>
									<option value="3">百度地图GPS地址更新任务</option>
								</select>
								</td>
							</tr>
								<tr id="normalTask">
									<th>普通任务内容:</th>
									<td>
										<table border="0" cellpadding="0" cellspacing="1" class="table_form">
											<tr>
											    <th>执行类型：</th>
												<td>
													<select id="executeType" name="executeType" class="easyui-combobox" style="width:160px">
														<option value="class">JAVA类</option>
														<option value="sql">SQL语句</option>
														<option value="proc">存储过程</option>
													</select>
												</td>
											</tr>	
											<tr>
												<th>执行内容：</th>
												<td>
													<input type="text" name="executeContent" id="executeContent" style="width:300px;" class="Itext"></input>
												</td>
											</tr>
											<tr>
												<th>执行参数：</th>
												<td>
													<textarea name="executeParam" id="executeParam" style="width:300px;"></textarea>
												</td>
											</tr>
										</table>
									</td>
								</tr>
								<tr id="noticeTask" style="display:none;">
									<th>预警通知任务内容:</th>
									<td>
										<table border="0" cellpadding="0" cellspacing="1" class="table_form">
											<tr>
												<th>模块实体名：</th>
												<td>
													<input type="text" name="moduleKey" id="moduleKey" style="width:300px;"  class="Itext"></input>
													（如：test.MainTable）
												</td>
											</tr>
											<tr>
												<th>查询sql语句：</th>
												<td>
													<textarea name="querySql" id="querySql" style="width:300px;height:80px;"></textarea>
												</td>
											</tr>
											<tr>
												<th>通知内容：</th>
												<td>
													<textarea name="noticeVal" id="noticeVal" style="width:300px;height:40px;"></textarea>
												</td>
											</tr>
											<tr>
											    <th>通知目标类型：</th>
												<td>
													<select id="destType" name="destType" class="easyui-combobox" style="width:160px">
														<option value="owner">单据所有者</option>
														<option value="role">指定角色</option>
													</select>
												</td>
											</tr>	
											<tr>
												<th>通知目标：</th>
												<td>
													<input type="text" name="destVal" id="destVal" class="easyui-validatebox Itext" style="width:300px;"></input>
												</td>
											</tr>
										</table>
									</td>
								</tr>
								<tr id="gpsUpdateTask" style="display:none;">
									<th>百度地图GPS地址更新任务:</th>
									<td>
										<table border="0" cellpadding="0" cellspacing="1" class="table_form">
											<tr>
												<th>查询sql语句：</th>
												<td>
													<textarea name="querySql" id="gpsQuerySql" style="width:300px;height:80px;"></textarea>
												</td>
											</tr>
											<tr>
												<th>更新sql语句：</th>
												<td>
													<textarea name="updateSql" id="gpsUpdateSql" style="width:300px;height:80px;"></textarea>
												</td>
											</tr>
											<tr>
												<th>gps坐标类型：</th>
												<td>
													<select id="coordtype" name="executeType" class="easyui-combobox" style="width:160px">
														<option value="gcj02ll">国测局坐标</option>
														<option value="bd09ll">百度经纬度坐标</option>
														<option value="bd09mc">百度墨卡托米制坐标</option>
													</select>
												</td>
											</tr>
											<tr>
											    <th>注意事项：</th>
												<td>
													<p>查询sql语句用于查询需要更新gps经度纬度的记录，需要提供2个必须字段：id（记录id）与address（需要解析的地址），id用于进行记录更新；例如：select id, address from a</p>
													<p>更新sql语句用于更新gps经度纬度，需要提供三个参数：id（记录id），lat（精度），lng（纬度）；例如：update a set a.lat = :lat, a.lng = :lng where id = :id</p>
												</td>
											</tr>
										</table>
									</td>
								</tr>
						</tbody>
					</table>
					</form>								
				</div>
				<div region="south" border="false" style="text-align:right;height:30px;line-height:30px;">
					<a id="stSave" class="easyui-linkbutton" iconCls="icon-ok"
					href="javascript:void(0)" onclick="doSaveObj()"><s:text
						name="system.button.save.title" /></a> 
					<a class="easyui-linkbutton"
					iconCls="icon-cancel" href="javascript:void(0)" onclick="doCloseWindow()"><s:text
						name="system.button.cancel.title" /></a>
				</div>
			</div>	
		</div>	
	</div>
</body>
</html>